#define _CRT_SECURE_NO_WARNINGS
#include "Stack.h"

void stack_inite(ST* p)
{
	assert(p);
	p->data = NULL;
	p->top = -1;
	p->capacity = 0;
}

static void judge_capacity(ST* p)
{
	assert(p);
	if ((p->top + 1) == p->capacity)
	{
		int newcapacity = p->capacity == 0 ? 4 : 4 * p->capacity;
		st_data_type* tmp = (st_data_type*)realloc(p->data, sizeof(st_data_type) * newcapacity);
		if (tmp == NULL)
		{
			perror("EXPANSION");
			exit(-1);
		}
		p->data = tmp;
		p->capacity = newcapacity;
	}
}

void stack_push(ST* p, st_data_type x)
{
	assert(p);
	judge_capacity(p);
	p->top++;
	p->data[p->top] = x;
}


void stack_pop(ST* p)
{
	assert(p && !stack_empty(p));
	p->top--;
}

st_data_type stack_top(ST* p)
{
	assert(p && !stack_empty(p));
	return p->data[p->top];
}

int stack_size(ST* p)
{
	assert(p);
	return (p->top + 1);
}

bool stack_empty(ST* p)
{
	assert(p);
	return (p->top == -1);
}

void stack_destory(ST* p)
{
	assert(p);
	free(p->data);
	p->data = NULL;
	p->capacity = 0;
	p->top = -1;
}